package com.kakavr.util;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.google.common.collect.Maps;
import com.kakavr.base.constant.SessionConstant;

/**
 * 存储用户信息到session中
 * 
 * @author gang.yang
 */
public class SessionUtils{

	public static HttpServletRequest getRequest() {
		ServletRequestAttributes sras = (ServletRequestAttributes) RequestContextHolder.currentRequestAttributes();
		return sras.getRequest();
	}

	public static HttpSession getSession(boolean allowCreate) {
		return getRequest().getSession(allowCreate);
	}

	public static HttpSession getSession() {
		return getSession(true);
	}

	public static void set(String key, Object o) {
		getSession().setAttribute(key, o);
	}

	public static Object get(String key) {
		return getSession().getAttribute(key);
	}
	
	@SuppressWarnings("unchecked")
	public static Map<String, Object> getCurUser() {
		if (null == get(SessionConstant.USER_TAG)) {
			return Maps.newHashMap();
		}
		return (Map<String, Object>) get(SessionConstant.USER_TAG);
	}

	/**
	 * 保存用户信息到session
	 * 
	 * @param user
	 */
	public static void setCurUser(Map<String, Object> user) {
		set(SessionConstant.USER_TAG, user);
	}

	/**
	 * 获取用户id
	 * 
	 * @return id
	 */
	public static Long getUserId() {
		Object obj = getCurUser().get("id");
		if (null == obj) {
			return null;
		}
		return (Long) obj;
	}
	
	/**
	 * 获取密码
	 * @return
	 */
	public static String getPass(){
		return (String)getCurUser().get("password");
	}
	
	/**
	 * 获取合伙人id
	 * @return
	 */
	public static Long getPartnerId(){
		Map<String,Object> user = getCurUser();
		int isPartner = (int) user.get("isPartner");
		if(isPartner == 1){
			return (Long) user.get("id");
		}
		return null;
	}
	
	public static Long getShopId(){
		Object obj = getCurUser().get("shopId");
		if (null == obj) {
			return null;
		}
		return (Long) obj;
	}

	/**
	 * 修改session中用户信息
	 * 
	 * @param key
	 *            用户key
	 * @param value
	 *            值
	 */
	public static void updateCurUser(String key, Object value) {
		Map<String, Object> map = getCurUser();
		map.put(key, value);
		set(SessionConstant.USER_TAG, map);
	}
}
